package cn.chenyumeng.blog.util;

import org.commonmark.Extension;
import org.commonmark.ext.gfm.tables.TableBlock;
import org.commonmark.ext.gfm.tables.TablesExtension;
import org.commonmark.ext.heading.anchor.HeadingAnchorExtension;
import org.commonmark.node.Link;
import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * @program: blog->MarkdownUtils
 * @description:
 * @author: cg
 * @create: 2020-09-19 16:54
 **/
public class MarkdownUtils {

    /**
     * Markdown格式转Html格式
     * @param markdown
     * @return
     */
    public static String markdownToHtml(String markdown) {
        Parser parser = Parser.builder().build();
        Node document = parser.parse(markdown);
        HtmlRenderer renderer = HtmlRenderer.builder().build();
        return renderer.render(document);
    }

    /**
     * 添加扩展（标题锚点、表格生成）
     * Markdown格式转Html格式
     * @param markdown
     * @return
     */
    public static String markdownToHtmlExtensions(String markdown) {
        // h标题生成id
        Set<Extension> headingAnchorExtensions = Collections.singleton(HeadingAnchorExtension.create());
        // 转换table的Html
        List<Extension> tablesExtension = Arrays.asList(TablesExtension.create());
        Parser parser = Parser.builder().extensions(tablesExtension).build();
        Node document = parser.parse(markdown);
        HtmlRenderer renderer = HtmlRenderer.builder()
                .extensions(headingAnchorExtensions)
                .extensions(tablesExtension)
                .attributeProviderFactory(attributeProviderContext -> (node, s, map) -> {
                    if (node instanceof Link) {
                        map.put("target", "_blank");
                    }
                    if (node instanceof TableBlock) {
                        map.put("class", "ui celled table");
                    }
                })
                .build();
        return renderer.render(document);
    }

}
